package com.syn.vr.util;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;

import com.gaoyi.basemodule.baseUtil.DateFormatUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {

    public static final int BACKUP_SUCCESS = 2000;
    public static final int BACKUP_FAIL = 3000;
    public static final int BACKUP_EMPTY = 4000;

    /**
     * 寫入生成的唯一標識碼
     */
    public static void writeInstallationFile(File installation, String androidId) {
        try {
            FileOutputStream fos = new FileOutputStream(installation);
            fos.write(androidId.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 複製數據庫文件到targetDir目錄下
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void copyDBToSD(Context context, Handler handler, DocumentFile targetDir) {
        String DB_MIME_TYPE = "application/vnd.sqlite3";
        String time = DateFormatUtil.DateTimeToStr(new Date(), "yyyyMMddHHMMss");
        File databaseDir = new File(context.getDataDir().getAbsolutePath() + "/databases");
        if (!databaseDir.exists()) {
            handler.sendEmptyMessage(FileUtil.BACKUP_EMPTY);
            return;
        }
        File[] files = databaseDir.listFiles();
        if (files == null) {
            handler.sendEmptyMessage(FileUtil.BACKUP_EMPTY);
            return;
        }
        boolean isSuccess = true;
        for (File file : files) {
            String fileName = file.getName();
            if (fileName.startsWith("vr.")) {
                DocumentFile targetFile;
                String[] split = fileName.split("\\.");
                targetFile = targetDir.createFile(DB_MIME_TYPE, split[0] + "_" + time + "." + split[1]);
                if (targetFile == null) {
                    handler.sendEmptyMessage(FileUtil.BACKUP_FAIL);
                    break;
                }
                isSuccess = copyFileToSD(context, file, targetFile);
            }
        }
        if (isSuccess) {
            handler.sendEmptyMessage(FileUtil.BACKUP_SUCCESS);
        } else {
            handler.sendEmptyMessage(FileUtil.BACKUP_FAIL);
        }
    }

    private static boolean copyFileToSD(Context context, File sourceFile, DocumentFile targetFile) {
        InputStream is = null;
        OutputStream os = null;
        try {
            ContentResolver resolver = context.getContentResolver();
            is = resolver.openInputStream(Uri.fromFile(sourceFile));
            os = resolver.openOutputStream(targetFile.getUri());

            byte[] buffer = new byte[4096];
            int byteRead;
            long readLength = 0;
            while (-1 != (byteRead = is.read(buffer))) {
                os.write(buffer, 0, byteRead);
                readLength += 4096;
            }
            os.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                if (sourceFile != null) {
                    sourceFile.setReadable(true);
                    sourceFile.setWritable(true);
                    sourceFile.setExecutable(true);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static File writeLog(Context context, String logType, String text) {
        String fileName = logType + DateFormatUtil.DateTimeToStr(new Date(),"yyyyMMdd") + ".txt";
        return writeTxt2File(context, text, fileName);
    }

    public static File writeTxt2File(Context context, String content, String fileName) {
        File file = createFile(context, fileName);
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(content.getBytes());
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static File createFile(Context context, String name) {
        if (hasSdcard()) {
            File[] dirs = ContextCompat.getExternalFilesDirs(context, null);
            if (dirs.length > 0) {
                File dir = dirs[0];
                return new File(dir, name);
            }
        }
        return null;
    }

    private static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
}
